package it.sciuto.turbosmswidget;

import android.app.ListActivity;
import android.appwidget.AppWidgetManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ContactsActivity extends ListActivity {
	private ListView listView;
	private Cursor cursor;

	private SharedPreferences settings;
	private Editor editor;
	private SimpleCursorAdapter listAdapter;

	private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Bundle extras = getIntent().getExtras();
		if (extras != null)
			appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

		settings = getSharedPreferences(ConfigureActivity.PREFERENCE_FILENAME + appWidgetId, MODE_PRIVATE);
		editor = settings.edit();

		cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
		startManagingCursor(cursor);

		String[] from = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID };

		// sets the items from above string to listview
		int[] to = { android.R.id.text1, android.R.id.text2 };

		// new listadapter, created to use android checked template
		listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to);
		setListAdapter(listAdapter);

		listView = getListView();
		// listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Cursor contactCursor = (Cursor) listView.getItemAtPosition(position);

				editor.putString(ConfigureActivity.PREFERENCE_NAME, contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
				editor.putString(ConfigureActivity.PREFERENCE_PHONE_NUMBER, contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
				editor.commit();

				finish();
			}

		});
	}

	@Override
	protected void onDestroy() {
		cursor.close();
		super.onDestroy();
	}
}